package top.yuzt.noticeserver.controller;


import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import top.yuzt.noticeserver.entity.Groupmembers;
import top.yuzt.noticeserver.entity.Usergroups;
import top.yuzt.noticeserver.mapper.GroupmembersMapper;
import top.yuzt.noticeserver.mapper.UsergroupsMapper;
import top.yuzt.noticeserver.service.impl.GroupmembersServiceImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuzt
 * @since 2024-05-05
 */
@RestController
@RequestMapping("/groupmembers")
public class GroupmembersController {
    @Autowired
    private GroupmembersMapper groupmembersMapper;

    @Autowired
    private UsergroupsMapper usergroupsMapper;
    //根据用户id查询组

    @Autowired
    private GroupmembersServiceImpl groupmembersService;
    public List<Groupmembers> gettGroupid(String id){

        List<Groupmembers> groupmembersList = groupmembersMapper.findGroupByUserid(id);
        return groupmembersList;

    }
    @GetMapping("/finduser")
    public List<Groupmembers> gettGroupmember(String id){
        List<Groupmembers> groupmembersList = groupmembersMapper.findUserByGroupid(id);
        return groupmembersList;
    }

    @PostMapping("/find")
    public List<Usergroups> selectGroup(@RequestBody String id){

        List<Usergroups> usergroupsList = new ArrayList<>();
        List<Groupmembers> grouplist = gettGroupid(id);
        for(Groupmembers x : grouplist){
            usergroupsList.addAll(usergroupsMapper.findUserGroupsByGroupID(x.getGroupid()));
        }
        System.out.println(usergroupsList);
        return usergroupsList;
    }

    @GetMapping("/setadmin")
    public boolean setadmin(Integer groupid,Integer userid){
        System.out.println(groupid);
        Groupmembers groupmembers = groupmembersMapper.findByGroupIdAndUserId(groupid,userid);
        groupmembers.setRole(1);
        return groupmembersService.saveOrUpdate(groupmembers);
    }

    @GetMapping("/removeadmin")
    public boolean removeadmin(Integer groupid,Integer userid){
        Groupmembers groupmembers = groupmembersMapper.findByGroupIdAndUserId(groupid,userid);
        groupmembers.setRole(0);
       return groupmembersService.saveOrUpdate(groupmembers);
    }

    @GetMapping("/removeuser")
    public boolean removeuser(Integer groupid,Integer userid){
        Groupmembers groupmembers = groupmembersMapper.findByGroupIdAndUserId(groupid,userid);
        return groupmembersService.removeById(groupmembers.getId());
    }

    @PostMapping("/save")
    public boolean save(@RequestBody Groupmembers groupmembers){
        return groupmembersService.save(groupmembers);
    }
}
